#include <iostream>
#include <string>
#include <errno.h>
#include <cstring>
#include <cstdlib>
#include <pthread.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "Log.hpp"
#include "LockGuard.hpp"

using namespace std;

void Usage(string proc)
{
    cout << "Usage:\n\t" << proc << " serverip serverport\n"
         << endl;
}

// ./tcpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        cerr << "socket error" << endl;
        exit(2);
    }

    // 不需要显示的绑定
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        cerr << "connect error" << endl;
        exit(2);
    }
    while(true)
    {
        cout<<"Please Enter# ";
        string outstring;
        getline(cin,outstring);
        ssize_t s=send(sockfd,outstring.c_str(),outstring.size(),0);
        if(s>0)
        {
            char inbuffer[1024];
            ssize_t m=recv(sockfd,inbuffer,sizeof(inbuffer)-1,0);
            if(m>0)
            {
                inbuffer[m]=0;
                cout<<inbuffer<<endl;
            }
        }
        else
        {
            break;
        }
    }

    close(sockfd);
    return 0;
}